<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'form/gform_ctrl_with_obj.class.php');

require_once('user_form.class.php');
require_once('user_form_view.class.php');

require_once($WSC->get_site_inc_dir().'modules/user_auth_basic/classes/user_bfpwd_dbc.class.php');


class User_Form_Ctrl extends GForm_Ctrl_With_Object {
	protected function create_form() {
		$form = new User_Form();

//		$form->generate_html();
		return $form;
	}


	protected function create_form_view() {
		$ret = new User_Form_View($this->form);

		return $ret;
	}


	protected function on_good_submit() {
		$ret = true;

		if (!ereg("^[a-z]{1}[a-z0-9_]{0,254}$", $this->form->get_field_value('username'))) {
			$this->form->set_field_error('username', 'invalid_username');

			$ret = false;
		}

		if ($this->form->get_field_value('password') == $this->form->get_field_value('password2')) {

			$dbc = $this->get_dbc();

			$object = $this->get_object();
			if ($object->get_id())  {
				if (User_DBC::username_exists_update($dbc, $this->form->get_field_value('username'), '', $object->get_id())) {
					$this->form->set_field_error('username', 'username_taken');
					$ret = false;
				}
			} else {
				if (User_DBC::username_exists($dbc, $this->form->get_field_value('username'), '')) {
					$this->form->set_field_error('username', 'username_taken');
					$ret = false;
				}
			}

			if ($ret) {
				if (tangra_strlen($this->form->get_field_value('password2')) <= 4) {

					$this->form->set_field_error('password2', 'weak_password');

					$ret = false;
				}
			}
		} else {
			$this->form->set_field_error('password2', 'passwords_not_match');
			$ret = false;
		}

		return $ret;
	}


	protected function on_bad_submit() {

//		printbr('lajna');
	}


	protected function create_object() {
		$object = new User_BFPwd_DBC();

		return $object;
	}


	protected function transfer_obj2form() {
		$object = $this->get_object();
		$form = $this->get_form();

		$form->set_field_value('username', $object->get_username());
		$form->set_field_value('password', $object->get_password());
		$form->set_field_value('disabled', $object->get_disabled());
	}


	protected function transfer_form2obj() {
		$object = $this->get_object();
		$form = $this->get_form();

		$object->set_username($form->get_field_value('username'));
		$object->set_password($form->get_field_value('password'));
		$object->set_disabled($form->get_field_value('disabled'));
	}
}